import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../../services/auth_service.dart';

class RegisterLogic extends GetxController {
  final AuthService _authService = AuthService();

  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  final ageController = TextEditingController();
  final selectedGender = ''.obs;

  final isLoading = false.obs;

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    ageController.dispose();
    super.onClose();
  }

  Future<void> register() async {
    // Validate inputs
    if (usernameController.text.isEmpty ||
        passwordController.text.isEmpty ||
        confirmPasswordController.text.isEmpty ||
        ageController.text.isEmpty ||
        selectedGender.value.isEmpty) {
      SmartDialog.showToast('所有字段都必须填写');
      return;
    }

    if (passwordController.text != confirmPasswordController.text) {
      SmartDialog.showToast('两次输入的密码不一致');
      return;
    }

    // Validate age is a number
    int? age = int.tryParse(ageController.text.trim());
    if (age == null || age <= 0) {
      SmartDialog.showToast('请输入有效的年龄');
      return;
    }

    isLoading.value = true;

    try {
      bool success = await _authService.register(
        usernameController.text.trim(),
        passwordController.text.trim(),
        age,
        selectedGender.value,
      );

      if (success) {
        SmartDialog.showToast('注册成功，请登录');
        Get.back(); // Return to login page
      } else {
        SmartDialog.showToast('用户名已存在');
      }
    } catch (e) {
      SmartDialog.showToast('注册失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  void goBack() {
    Get.back();
  }
}
